package com.chenxin.transaction.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.chenxin.transaction.dao.ZhangsanAccountInfoDao;
import com.chenxin.transaction.entity.AccountChangeEvent;
import com.chenxin.transaction.service.AccountInfoService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description:
 * @title: ZhangsanTxmsgAccountServieImpl
 * @Author Star_Chen
 * @Date: 2022/5/31 11:37
 * @Version 1.0
 */
@Service("zhangsanTxmsgAccountServiceImpl")
public class ZhangsanTxmsgAccountServiceImpl implements AccountInfoService {

    @Autowired
    private ZhangsanAccountInfoDao zhangsanAccountInfoDao;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void updateAccountBalance(String accountNo, Double amount) {
        return;
    }

    /**
     * @param accountChangeEvent :
     * @Date: 2022/5/31 22:04
     * @Description: 向mq发转账消息
     * @Return: * @return : void
     */
    @Override
    public void sendUpdateAccountBalance(AccountChangeEvent accountChangeEvent) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("accountChange", accountChangeEvent);
        String jsonString = jsonObject.toJSONString();
        Message<String> message = MessageBuilder.withPayload(jsonString).build();
        rocketMQTemplate.sendMessageInTransaction("producer_group_txmsg_bank1", "topic_txmsg", message, null);
    }
    /**
     * @Date: 2022/6/1 22:15
     * @Description: 转账
     * @param accountChangeEvent :
     * @Return:  * @return : void
     */
    @Override
    @Transactional
    public void doUpdateAccountBalance(AccountChangeEvent accountChangeEvent) {
        //幂等判断,如果存在此事务，就无需更新
        if (zhangsanAccountInfoDao.isExistTx(accountChangeEvent.getTxNo()) > 0) {
            return;
        }

        //扣减金额
        zhangsanAccountInfoDao.updateAccountBalance(accountChangeEvent.getAccountNo(), accountChangeEvent.getAmount()*-1);
        zhangsanAccountInfoDao.addTx(accountChangeEvent.getTxNo());
        if (accountChangeEvent.getAmount() == 3) {
            throw new RuntimeException("人为制造异常！");
        }
    }
}
